package joctave.ui.awt;

import joctave.core.functions.FunctionParser;
import joctave.core.functions.UserFunction;

import joctave.core.interpreter.ErrorLogger;
import joctave.core.interpreter.Interpreter;
import joctave.core.interfaces.JOctaveOutput;
import joctave.core.interfaces.RemoteAccessible;
import joctave.ui.common.Console;
import joctave.ui.swing.CommandHistoryManager;

import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

import javax.swing.JFileChooser;


/**
 * Simple GUI for the JMathLib package.

 * Some options may be given in the command line, by example:
 * <kbd>localhost# java jmathlib.ui.awt.GUI -width=320 -height=200</kbd>.
 * <p>
 * <b>Command line options</b>
 * <ul>
 * <li><kbd>-width</kbd> - The width of the main window</li>
 * <li><kbd>-height</kbd> - The height of the main window</li>
 * </ul>
 * </p>
 */
public class GUI extends Frame implements JOctaveOutput, WindowListener, ActionListener, RemoteAccessible, ClipboardOwner
{
    /*The menubar container.*/
    private MenuBar  mainMenuBar;
    private Menu     fileMenu;
    private Menu     editMenu;
    private Menu     windowMenu;
    private Menu     recentMenu;
    private Menu     helpMenu;
    private MenuItem separator1;
    private MenuItem separator2;
    private MenuItem newFileMenuItem;
    private MenuItem openFileMenuItem;
    private MenuItem saveFileMenuItem;
    private MenuItem saveAsFileMenuItem;
    private MenuItem configMenuItem;
    private MenuItem checkForUpdatesMenuItem;
    private MenuItem exitFileMenuItem;
    private MenuItem cutEditMenuItem;
    private MenuItem copyEditMenuItem;
    private MenuItem pasteEditMenuItem;
    private MenuItem consoleWindowMenuItem;
    private MenuItem plotWindowMenuItem;
    private MenuItem aboutHelpMenuItem;
    private MenuItem helpMenuItem;

    /** status message in frame */
    private Label    statusLabel;
    
    /**Constant with the application title.*/
    private final String TITLE="JOctave";

    /**The area used for user input and where the answers are displayed*/
    private Console answer;

    /**The interpreter*/
    private Interpreter interpreter;

    private File file;
    private Properties iniFile;
	private InputStream is;
	private OutputStream os;
	int numrecent=3;
    
	public static String extractFileName( String filePathName )
	  {
	    if ( filePathName == null )
	      return null;

	    int dotPos = filePathName.lastIndexOf( '.' );
	    int slashPos = filePathName.lastIndexOf( '\\' );
	    if ( slashPos == -1 )
	      slashPos = filePathName.lastIndexOf( '/' );

	    if ( dotPos > slashPos )
	    {
	      return filePathName.substring( slashPos > 0 ? slashPos + 1 : 0,
	          dotPos );
	    }

	    return filePathName.substring( slashPos > 0 ? slashPos + 1 : 0 );
	}
	
	String getRunPath()
	{
    	String path=GUI.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    	String dir;
    	if (path.indexOf(".jar")>=0) {
    		File f = new File(path);
    		return  f.getParent();
    		//System.out.println("dfmmmmM"+java.io.File.pathSeparatorChar+" "+path);
    		//dir=path.substring(0, path.lastIndexOf(java.io.File.pathSeparatorChar));

    	}else
    		return null;
		
	}
	
    
	void openFile(String filepath,String filename) 
	{
		try
		{
			//URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
	        //System.out.println(location.getFile());
			//System.out.println("cfdf"+System.getProperty("user.dir")+" "+ theFileDialog.getDirectory()+ " "+theFileDialog.getFile()+" "+ new File(".").getAbsolutePath());
	    	BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream( filepath+filename)));
	    	try {
	    		//String lines=br.re
	    	    String lines="";
	    	    String line;
	    	    String func="";
	    	    boolean infunc=false;
	    	    while ((line = br.readLine()) != null) {
	    	    	if (line.length()>10&&line.charAt(0)!='#'&&!infunc&&line.indexOf("function")>=0)  {
		    			infunc=true;
		    			func="";	            	    		
	    	    	}
	    	        // process line
	    	        if (infunc)
	    	        	func+=line+"\n";
	    	        else {
	    	        	if (line.length()>0&&line.charAt(0)!='#'&&line.indexOf(";")<0&&
	    	        			line.trim().split(" ").length==1&&line.trim().split("\\(").length==1&&line.trim().split("=").length==1&&
	    	        		!line.trim().equals("else")&&!line.trim().equals("end")&&!line.trim().equals("endif")&&!line.trim().equals("endfunction"))
	    	        		line="disp(strcat('ans = ',"+line.trim()+"));";
	    	        		//line="disp('ans = '+"+line.trim()+");";
	    	        	lines+=line+"\n";
	    	        }
	    	        
	    	    	if (line.length()>10&&line.charAt(0)!='#'&&infunc&&line.indexOf("endfunction")>=0)  {
		    			infunc=false;
	                    FunctionParser funcParser = new FunctionParser();
	                    UserFunction function = funcParser.parseFunction(func);
	                    interpreter.globals.getFunctionManager().getFunctionLoader(0).clearCachedFunction(function.getName());
	                    interpreter.globals.getFunctionManager().getFunctionLoader(0).cacheFunction(function);
		    			
	    	    	}
	    	    	//this.interpretLine(line);
	    	    }
	    	    //interpreter.
	    	    //.executeExpression(line
	    	    this.interpretLine(lines);
	    	    //answer.appendText(lines);
	            // set name of user function
	            // remember: the name of the called function could be different compared
	            // to the function's name inside the m-file
	            //function.setName(functionName);
	            
	            //addUserFunction(userFunc);
	            //cacheFunction(function);	            		
	    		
	    	} finally {
	    	    br.close();
	    	    String fullfilename=filepath+filename;
	    	    for (int i=numrecent-1; i>=0; i--) {
	    	    	String property=(i+1)+"";
	    	    	if (iniFile.getProperty(property)!=null&&iniFile.getProperty(property).equals(fullfilename)) {
	    	    		iniFile.remove(property);
	    	    		//for (int j=i; j<numrecent-1; j++)
	    	    		//	iniFile.setProperty((j+1)+"", iniFile.getProperty((j+2)+""));
	            	    for (int j=numrecent-1; j>=i; j--) {
	            	    	String property2=(j+1)+"";
	            	    	String val="";
	            	    	if (iniFile.getProperty((j)+"")!=null)
	            	    		val=iniFile.getProperty((j)+"");
	            	    	iniFile.setProperty(property2, val);
	            	    }	            	    	
	                }
	    	    }
	    	    for (int i=numrecent-1; i>=1; i--) {
	    	    	String property=(i+1)+"";
	    	    	String val="";
	    	    	if (iniFile.getProperty((i)+"")!=null)
	    	    		val=iniFile.getProperty((i)+"");
	    	    	iniFile.setProperty(property, val);
	    	    }
		    	iniFile.setProperty("1", fullfilename);
		    	for (int i=0; i<numrecent; i++) {
	    	    	String val="";
	    	    	if (iniFile.getProperty((i+1)+"")!=null)
	    	    		val=iniFile.getProperty((i+1)+"");
		        	MenuItem menuItem;
		        	String label=extractFileName(val);
		        	if (recentMenu.getItemCount()<=i) {
		        		menuItem=new MenuItem();//val,label);
		        		recentMenu.add(menuItem);
		        		menuItem.addActionListener(this);
		        	} else		        		
		        		menuItem=recentMenu.getItem(i);
	        		menuItem.setName(val);
	        		menuItem.setLabel(label);
		    	}
	    	} 
	    } catch (IOException ioe) {
	        ioe.printStackTrace();
	    }  
	}


	
    /**Reacts to the user menu and update (if necessary) the interface.*/
    public void actionPerformed(ActionEvent e)
    {
        Object o = e.getSource();

        System.out.println("ffill"+((MenuItem)o).getName());
        if (o instanceof MenuItem&&((MenuItem)o).getName().indexOf(".m")>0) {
        	String fname=((MenuItem)o).getName();
        	if (fname.indexOf(java.io.File.separator)<0&&getRunPath()!=null)
            	openFile(getRunPath()+java.io.File.separator,((MenuItem)o).getName());
        	else
            	openFile("",((MenuItem)o).getName());
           // System.out.println("uudff"+((MenuItem)o).getLabel());
        	//java.io.File.separator
        } else if (o == newFileMenuItem)  {
        	 answer.setText("");
        }   else if (o == openFileMenuItem)  {
        	String path=GUI.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        	String dir=getRunPath();
        	/*if (path.indexOf(".jar")>=0) {
        		File f = new File(path);
        		dir = f.getParent();
        		//System.out.println("dfmmmmM"+java.io.File.pathSeparatorChar+" "+path);
        		//dir=path.substring(0, path.lastIndexOf(java.io.File.pathSeparatorChar));

        	}else
        		dir=null;*/
        	//System.out.println("dfd"+dir);
            FileDialog theFileDialog = new FileDialog(this, "Open the file...", FileDialog.LOAD);
            if (dir!=null)
            	theFileDialog.setDirectory(dir);
           // open.dialog.in.file.directory=1
            theFileDialog.setVisible(true);
           
            if (theFileDialog.getFile()!=null)   {
            	
            	openFile(theFileDialog.getDirectory(),theFileDialog.getFile());
            }
        } 
        else if (o == saveFileMenuItem) 
        {
            FileDialog theFileDialog = new FileDialog(this, "Save the file", FileDialog.SAVE);
            theFileDialog.show();
            if (theFileDialog.getFile()!=null)   {
                File f = new File(theFileDialog.getFile());
                		//jFileChooser1.getSelectedFile();
               // if (!f.getName().endsWith(".msw")) 
              //  {
               //     f = new File(f.getAbsolutePath() + ".msw");
              //  }
                saveWorkspace(f);
            }
        }  else if (o == saveAsFileMenuItem)   {
            FileDialog theFileDialog = new FileDialog(this, "Save the file", FileDialog.SAVE);
            theFileDialog.setVisible(true);
        }   else if (o == configMenuItem)    {
        	ConfigGUIDialog configDialog = new ConfigGUIDialog(this);  
        	ErrorLogger.setDebug(configDialog.debugCheckbox.getState());
        	//System.out.println("confi"+configDialog.debugCheckbox.getState());
        } else if (o == checkForUpdatesMenuItem)   {
            String answerString = interpreter.executeExpression("checkforupdates()");
            answer.displayText(answerString);
            answer.displayPrompt();
        } 
        else if (o == exitFileMenuItem) 
        {
        	close();
        } 
        else if (o == cutEditMenuItem) 
        {
        	// get text from textarea
        	String          s    = answer.getSelectedText();

        	// replace selected text with empty string
        	answer.replaceRange("", answer.getSelectionStart(), answer.getSelectionEnd());

        	// copy selected string to system clipboard
        	StringSelection sel  = new StringSelection(s);
        	Clipboard       clip = getToolkit().getSystemClipboard();
        	clip.setContents(sel, this);
        } 
        else if (o == copyEditMenuItem) 	
        {
        	// get text from textarea
        	String          s    = answer.getSelectedText();

        	// copy selected string to system clipboard
        	StringSelection sel  = new StringSelection(s);
        	Clipboard       clip = getToolkit().getSystemClipboard();
        	clip.setContents(sel, this);
        } 
        else if (o == pasteEditMenuItem)  {
        	// paste from system clipboard to textarea
        	Clipboard    clip = getToolkit().getSystemClipboard();
        	Transferable cont = clip.getContents(this);
        	if (cont!=null)
        	{
        		try 
        		{
        			String s = (String)cont.getTransferData(DataFlavor.stringFlavor);
        			answer.insert(s, answer.getCaretPosition());
        		}
        		catch (Exception ex)
        		{
        			ErrorLogger.debugLine("clipboard not STRING");
        		}
        	}
        }  else if (o == aboutHelpMenuItem)    {
            AboutGUIDialog aboutDialog = new AboutGUIDialog(this);
        } else if (o == helpMenuItem)  {
        	try {
				Desktop.getDesktop().browse(new URI("https://code.google.com/p/joctave/wiki/PageName"));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (URISyntaxException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        }  else if (o == consoleWindowMenuItem) 
        {
            this.setTitle(TITLE + " Console");
            plotWindowMenuItem.setEnabled(true);
            consoleWindowMenuItem.setEnabled(false);
        } 
        else if (o == plotWindowMenuItem) 
        {
            this.setTitle(TITLE + " Plot");
            plotWindowMenuItem.setEnabled(false);
            consoleWindowMenuItem.setEnabled(true);
        }
    } // end actionPerformed

   
    /**
     * @param
     * @param
     */
    public void lostOwnership(Clipboard clip, Transferable cont)
    {
    	ErrorLogger.debugLine("clipboard has been changed");
    }

    /**
     * Command-line parameter handler
     * Takes control of the size of the main window
     */
    private void argumentHandler(String[] args)
    {
        int width  = -1;
        int height = -1;

        // Parse all the arguments (or parameters)
        for (int i=0; i<args.length; i++)
        {
            String s;
            if  (args[i].startsWith("-width="))
            {
                s = args[i].substring(7);
                try
                {
                    width = Integer.valueOf(s).intValue();
                    if  (width < 0)
                        throw new NumberFormatException();
                }
                catch (NumberFormatException nfe)
                {
                    System.out.println(s + ": Invalid number.");
                    width = -1;
                }
            }
            else if  (args[i].startsWith("-height="))
            {
                s = args[i].substring(8);
                try
                {
                    height = Integer.valueOf(s).intValue();
                    if  (width < 0)
                    {
                        throw new NumberFormatException();
                    }
                }
                catch (NumberFormatException nfe)
                {
                    System.out.println(s + ": Invalid number.");
                    height = -1;
                }
            }
            else
                System.out.println(args[i] + ": Invalid option.");
        }
        
        // Let's resize the window...
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        if  (width == -1)
            width = (d.width*50)/100;
        
        if  (height == -1)
            height = (d.height*50)/100;

        this.setSize(width, height);
    }


    /**Function called when the gui is being close*/
    public void close()
    {
        try {
          os = new FileOutputStream(file);//Create a FileOutputStream

         // iniFile.setProperty("configini","blash");
          String sDebug;
          if  (ErrorLogger.getDebug())
        	  sDebug="1";
          else
        	  sDebug="0";
          iniFile.setProperty("debug",sDebug);
          iniFile.store(os, "");//write the Properties object values to our ini file
          os.close();//close

 
        }	catch(Exception n){System.out.println(n+"");}


        interpreter.save();
        this.dispose();
        System.exit(0);
    }
    
    /**Create the main graphical interface (menu, buttons, delays...).*/
    public GUI(String[] args)
    {
    	
        this.argumentHandler(args);

        //System.out.println("dfsdfs"+GUI.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        try	{
        	String dir=getRunPath();
        	if (dir!=null) {
        		//System.out.println("inin"+dir+"joctave.ini"+ "  "+java.io.File.pathSeparator+"nnn"+java.io.File.separator);
        		file = new File(dir+java.io.File.separator+"joctave.ini");//This is out ini file
        	} else
        		file = new File("joctave.ini");//This is out ini file
			file.createNewFile();
			is = new FileInputStream(file);//Create a FileInputStream
            iniFile = new Properties();
			iniFile.load(is);//load the ini to the Properties file
			is.close();//close
			//iniFile.getProperty("config")


		}	catch(Exception n){System.out.println(n+"");}
        
        this.setVisible(false);
        this.setLayout(new BorderLayout());
        this.setBackground(new Color(214,211,206));

        //Get the size of the screen
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        //position the frame in the centre of the screen
        this.setLocation((d.width-getSize().width) / 2,
                         (d.height-getSize().height) / 2);
        this.addWindowListener(this);
        this.setResizable(true);
        this.setVisible(true);
        
        // add image to window
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image icon = tk.getImage(GUI.class.getResource("icon.jpg"));//smalllogo.gif"));
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(icon,0);
        try {
            mt.waitForAll();
        }
        catch (InterruptedException e){ ;}
        this.setIconImage(icon);
        
        this.setTitle(TITLE + " [1/4] Initializing menus");
        InitMenuBar(this);

        this.setTitle(TITLE + " [2/4] Initializing console window");
        answer = new Console(this);
        answer.setFont(new Font("Monospaced", Font.PLAIN, 11));
        this.add(answer, BorderLayout.CENTER);
        answer.displayPrompt();
        // Sometimes I get an unfocused console, so I request it manually.
        answer.requestFocus();


        statusLabel = new Label("JOctave");
        this.add(statusLabel, BorderLayout.SOUTH);
        

        this.validate();

        this.setTitle(TITLE + " [3/4] Initializing interpreter");
        interpreter = new Interpreter(true);
        interpreter.setOutputPanel(this); //answer);
        //interpreter.regStatus(statusLabel);
        
       
        this.setTitle(TITLE + " [4/4] running startup script");
        interpreter.executeExpression("startup;");
        //interpreter.executeExpression("messageoftheday");
        answer.displayPrompt();

        // silent check for updates
       // interpreter.executeExpression("checkforupdates('-silent')");

        this.setTitle(TITLE + " - Console Window");

        // in case an update is available inform the user
        String u = interpreter.globals.getProperty("update.newversionavailable");
        if ((u!=null) && u.equals("yes"))
        {
            this.setTitle(TITLE + " - (NEW version available: type update at prompt)");
            String s = interpreter.globals.getProperty("update.newversionavailable.message01");
            if (s==null)
                answer.displayText("A NEW version of JOctave is available\n     type update  ");
            else
                answer.displayText(s);
            
            answer.displayPrompt();
        }
        
        ErrorLogger.setDebug(iniFile.getProperty("debug")==null||!iniFile.getProperty("debug").equals("0"));
 
    } // end GUI


    
    /**The menu initializer.*/
    private void InitMenuBar(ActionListener listener)
    {
        mainMenuBar = new MenuBar();
        fileMenu = new Menu("File", true);
        mainMenuBar.add(fileMenu);
        editMenu = new Menu("Edit", true);
        mainMenuBar.add(editMenu);
       // windowMenu = new Menu("Window", true);
       // mainMenuBar.add(windowMenu);
        helpMenu = new Menu("Help", true);
        mainMenuBar.add(helpMenu);

        separator1 = new MenuItem("-");
        separator2 = new MenuItem("-");
        
        newFileMenuItem = new MenuItem("Clear");
        newFileMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_O));
        newFileMenuItem.addActionListener(listener);
        
        openFileMenuItem = new MenuItem("Open Script");
        openFileMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_O));
        openFileMenuItem.addActionListener(listener);
        
        saveFileMenuItem = new MenuItem("Save Output");
        saveFileMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_S));
        saveFileMenuItem.addActionListener(listener);
        
        configMenuItem = new MenuItem("Configuration");
        //configMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_S));
        configMenuItem.addActionListener(listener);
      //  saveAsFileMenuItem = new MenuItem("Save as...");
      //  saveAsFileMenuItem.addActionListener(listener);
        
        //checkForUpdatesMenuItem = new MenuItem("Check for updates");
       // checkForUpdatesMenuItem.addActionListener(listener);
        

        
        exitFileMenuItem = new MenuItem("Exit");
        exitFileMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_E));
        exitFileMenuItem.addActionListener(listener);
        
        cutEditMenuItem = new MenuItem("Cut");
        cutEditMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_X));
        cutEditMenuItem.addActionListener(listener);
        
        copyEditMenuItem = new MenuItem("Copy");
        copyEditMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_C));
        copyEditMenuItem.addActionListener(listener);
        
        pasteEditMenuItem = new MenuItem("Paste");
        pasteEditMenuItem.setShortcut(new MenuShortcut(KeyEvent.VK_V));
        pasteEditMenuItem.addActionListener(listener);
        
        /*consoleWindowMenuItem = new MenuItem("Console Window");
        consoleWindowMenuItem.setEnabled(false);
        consoleWindowMenuItem.addActionListener(listener);
        
        plotWindowMenuItem = new MenuItem("Plot Window");
        plotWindowMenuItem.addActionListener(listener);*/
        
        helpMenuItem = new MenuItem("Help");
        helpMenuItem.addActionListener(listener);
        aboutHelpMenuItem = new MenuItem("About...");
        aboutHelpMenuItem.addActionListener(listener);
        
        fileMenu.add(newFileMenuItem);
        fileMenu.add(openFileMenuItem);
        fileMenu.add(separator1);
        fileMenu.add(saveFileMenuItem);
        fileMenu.add(configMenuItem);
        //fileMenu.add(saveAsFileMenuItem);
        recentMenu=new Menu("Recent");

        fileMenu.add(recentMenu);
        for (int i=0; i<numrecent; i++) {
	        if (iniFile.getProperty((i+1)+"")!=null&&!iniFile.getProperty((i+1)+"").equals("")) {
	        	MenuItem menuItem=new MenuItem();
	        	String val=iniFile.getProperty((i+1)+"");//);
	        	String label=extractFileName(val);
	        	menuItem.setName(val);
	        	menuItem.setLabel(label);
	        	recentMenu.add(menuItem);
	        	menuItem.addActionListener(listener);
	        }
        }
        fileMenu.add(separator1);
        //fileMenu.add(checkForUpdatesMenuItem);
       // fileMenu.add(separator2);
        fileMenu.add(exitFileMenuItem);
        editMenu.add(cutEditMenuItem);
        editMenu.add(copyEditMenuItem);
        editMenu.add(pasteEditMenuItem);
        //windowMenu.add(consoleWindowMenuItem);
       // windowMenu.add(plotWindowMenuItem);
        helpMenu.add(helpMenuItem);
        helpMenu.add(aboutHelpMenuItem);

        this.setMenuBar(mainMenuBar);
    }

    /**
     * Interpret the last command line entered
     * @param
     */
    public void interpretLine(String line)
    {
        String answerString = interpreter.executeExpression(line);
        answer.displayText(answerString);
        answer.displayPrompt();
    }
    
    
    /**
     * displays the output of an evaluation
     * @param  text to display
     */
    public void displayText(String text)
    {
        answer.displayText(text);
    }
    
    /**
     * displays the current status message at the bottom of the frame
     * @param status  message
     */
    public void setStatusText(String status)
    {
        statusLabel.setText(status);
    }

    /**
     * main method
     * @param args
     */
    public static void main (String[] args)
    {
        GUI gui = new GUI(args);
    }

    /**
     * 
     */
    public void windowActivated(WindowEvent e)
    {
    }


    /**
     * 
     */
    public void windowClosed(WindowEvent e)
    {
    }

    /**
     * 
     */
    public void windowClosing(WindowEvent e)
    {
        close();
    }

    /**
     * 
     */
    public void windowDeactivated(WindowEvent e)
    {
    }

    /**
     * 
     */
    public void windowDeiconified(WindowEvent e)
    {
    }

    /**
     * 
     */
    public void windowIconified(WindowEvent e)
    {
    }

    /**
     * 
     */
    public void windowOpened(WindowEvent e)
    {
    }
    
    void saveWorkspace(File f) {
    	//displayText("pooo");
        try {
            FileWriter fw = new FileWriter(f);
           // this.setTitle(appTitle + " - " + f.getAbsolutePath());
            String s = answer.getText();
            setStatusText("Writing file...");
            fw.write(s);
            //answer.write(fw);
            fw.close();
            //this.statusBar.setText(s);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    

    /**
     * Load the specified workspace file.
     *
     * All the main window text and the command history is overwritten.
     * See release notes - General notes - GN0009
     * @param f File to load
     */
   /* void loadWorkspace(File f) {
        try {
            FileReader fr = new FileReader(f);
            //this.setTitle(appTitle + " - " + f.getAbsolutePath());
           // String s = this.statusBar.getText();
            setStatusText("Reading file...");
            this.answer.setText("");

            // Command History Vector
            char c = (char) fr.read();
            while (fr.ready()) {
                String line = "";
                // Read a line
                while (c != '\r' && c != '\n' && fr.ready()) {
                    line += c;
                    c = (char) fr.read();
                }
                // Skip new-lines (MAC, DOS or UNIX styles supported)
                char c2 = 0;
                while (c != c2 && fr.ready() && (c == '\n' || c == '\r')) {
                    c2 = c;
                    c = (char) fr.read();
                }
                // Test if it's a command
                if (line.startsWith("> ") && line.length() > 2) {
                    // Yes, it's a command
                    CommandHistoryManager.getDefaultInstance().addCommand(line.substring(2));
                }
                // Append the line to the main window
                if (fr.ready()) {
                    line += '\n';
                } else {
                    line += c;
                }
                this.answer.append(line);
            }

            // It's safer to uncomment the next line only when saving files
            // with unfinished operations (no prompt is shown)
            //// answer.append('\n' + "> ");
            answer.setCaretPosition(answer.getText().length());
          //  setStatusText(s);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
*/
    
}
